<?php

namespace addons\crontab\controller;

use addons\crontab\model\Crontab;
use app\admin\model\inventory\Kc;
use app\admin\model\inventory\Wmskc;
use app\admin\model\inventory\Procure;
use app\admin\model\inventory\Material;
use Cron\CronExpression;
use fast\Http;
use think\Controller;
use think\Db;
use think\Exception;
use think\Log;
use think\Request;

//use app\common\model\Temporary;
use app\admin\model\inventory\Temporary;
use app\admin\model\outhouse\Rdinrecord;
use app\admin\model\outhouse\Rdoutrecord;
use app\admin\model\outhouse\CheckVouchList;
use app\admin\model\outhouse\Kcmx;
use app\admin\model\information\Shelves;
use app\admin\model\Kisapi;
use app\admin\model\information\KisBaseinfo;
use app\admin\model\inventory\MaterialListView;

/**
 * 定时任务接口
 *
 * 以Crontab方式每分钟定时执行,且只可以Cli方式运行
 * @internal
 */
class Pda extends Controller
{
    /**
     * 初始化方法,最前且始终执行
     */
    public function _initialize()
    {
        // 只可以以cli方式执行
        /* if (!$this->request->isCli()) {
         $this->error('Autotask script only work at client!');
         }*/
        
        parent::_initialize();
        
        // 清除错误
        //error_reporting(0);
        
        // 设置永不超时
        set_time_limit(0);
    }
    
    /*
     * 接收pda单据到pc端
     *   */
    public function addPdaData($main,$detail,$type,$status){
        $type_arr = [
            '1'=>'外购入库',//收货
            '2'=>'选材料清单出库',//生产任务 材料清单出库
            '3'=>'其他入库',
            '4'=>'其他出库',
            //'5'=>'源单上架',
            '6'=>'采购退回',
            '7'=>'领料退回',
            '8'=>'调拨',
            '9'=>'盘点',
            //'10' => '直接上架', //首先得找到那种物料，不在货架上的数量，是否满足，如满足则直接上架
            '11' => '直接领料',
            '12' => '领料出库',//引源单，拣货后，形成拣货单，供下一步领料选择，拣货单出库
            '14' => '产品入库',
            '15' => '销售出库',
            '16' => '组装单'
        ];

        $temp_arr = [];
        $digits = getDigits();//默认小数位数
        
        //自动处理，就自动审核过
        $check_status = 0;
        if($status){
            $check_status = 1;
        }
        
        $code = $main['FBillNo'];//pda单据编码  //$main['source_code'];//源单编码
        $warehouseId = $main['stock_id'];//原仓库id
        $to_warehouseId = $warehouseId;//目标仓库id
        
        if(isset($main['a_remark'])){
            $remark = $main['a_remark'];//单据（表头）备注  pda出入单据
        }else if(isset($main['remark'])){
            $remark = $main['remark'];//单据（表头）备注  其他单据，例如调拨，盘点
        }
        
        //处理其他入库单表头
        if($type == 3){
            //表头
            db('rdinrecord')->insert([
                'code' => $code,
                'code_date' => $main['FDate'],
                'warehouse_id' => $to_warehouseId,
                'createtime'=>date('Y-m-d H:i:s'),
                'check_status' => $check_status,
                'status' => $status
            ]);
            Log::log($code . ':pda其他入库单表头完成'.'，锁单状态：'.$check_status==1?'锁单':'待锁');
        }
        
        //处理其他出库单表头
        if($type == 4){
            //表头
            db('rdoutrecord')->insert([
                'code' => $code,
                'code_date' => $main['FDate'],
                'warehouse_id' => $to_warehouseId,
                'createtime'=>date('Y-m-d H:i:s'),
                'check_status' => $check_status,
                'status' => $status
            ]);
            Log::log($code . ':pda其他出库单表头完成'.'，锁单状态：'.$check_status==1?'锁单':'待锁');
        }
        
        //处理调拨表头
        if($type == 8){
            $db_type = 1;//同库
            //异库调拨
            if($warehouseId!=$main['to_stock_id']){
                $db_type = 2;
                $to_warehouseId = $main['to_stock_id'];
                if(!$to_warehouseId){
                    exception('目标仓库ID输入有误');
                }
            }
            
            $tpdj = [
                'code'=>$code,
                'code_date'=>$main['FDate'],
                'warehouse_id'=>$warehouseId,
                'warehouse_change_id'=>$main['to_stock_id'],
                'warehouse_code'=>$warehouseId,
                'warehouse_change_code'=>$main['to_stock_id'],
                'type'=>$db_type,//默认0，1:同库，2:异库
                'tp_iQuantity'=>$main['totalnum'],
                'material_code' => $main['invStart']??'',//领料单号
                'status' => $status,
                'remark' => $remark
            ];
            
            \app\admin\model\outhouse\Tpdj::addData($tpdj); //添加表头
            Log::log($code . ':pda调拨表头完成');
        }

        //20240108针对pda提交上来的销售订单，同物料求和 ，重新整理后，形成新表体
        $sell_temp_arr = [];
        $qrNo_arr = [];
        if($type==15){
            $sell_temp_inv_arr = array_column((array)$detail,'inv_number');//提交上来的物料id数组
            $sell_temp_inv_arr = array_unique($sell_temp_inv_arr);//去掉重复，得到，提交上来的物料编码数组

            //循环旧表体记录，得到上传上来的物料总数（按批号计）
            foreach ($detail as $kk=>$vv){
                if(isset($sell_temp_arr[$vv['inv_number'].'_'.$vv['cBatch']])){
                    $sell_temp_arr[$vv['inv_number'].'_'.$vv['cBatch'].'_'.$vv['shelves_id']] += $vv['fqty'];
                }else{
                    $sell_temp_arr[$vv['inv_number'].'_'.$vv['cBatch'].'_'.$vv['shelves_id']] = $vv['fqty'];
                }

                if(!isset($qrNo_arr[$vv['inv_number'].'_'.$vv['cBatch']])&&$vv['inv_attributes']){
                    $qrNo_arr[$vv['inv_number'].'_'.$vv['cBatch']] = $vv['inv_attributes'];
                }
            }
            
            //数量，从小-》大，排列，方便下面扣减
            //asort($sell_temp_arr);
            ksort($sell_temp_arr);//从大到小 20240321
            //dump($sell_temp_arr);
            //得到所有提交上来的发货通知单明细
            $sell_order_arr = collection(MaterialListView::where([
                'material_code' => $main['source_code'],
                'inventory_number' => ['IN',$sell_temp_inv_arr],
                'status' => 1
            ])
            ->field('auto_id,row_id,inventory_number,no_quantity,fCoefficient')
            ->select())
            ->toArray();
            //dump($sell_order_arr);
            
            $deal_data = [];//新的表体明细，拆分好的
            if($sell_temp_arr&&$sell_order_arr){
                foreach($sell_temp_arr as $sk=>&$total_fqty){
                    $sk_arr = explode('_',$sk);//编码_批号_库区
                    foreach($sell_order_arr as &$sell_order){
                        if($sell_order['no_quantity']>0){
                            if($sell_order['inventory_number'] == $sk_arr[0]){
                                //同个物料,插入临时表
                                $thisqty = $sell_order['no_quantity'];
                                $total_fqty -= $sell_order['no_quantity'];
                                
                                if($total_fqty<0){
                                    $thisqty = $sell_order['no_quantity']+$total_fqty;
                                    $total_fqty = 0;
                                    $sell_order['no_quantity'] -= $thisqty;
                                }else{
                                    $sell_order['no_quantity'] = 0;
                                }

                                if($thisqty){
                                    //本次操作数量大于0的，加入临时数组
                                    $deal_data[] = [
                                        'auto_id' => $sell_order['auto_id'],
                                        'row_id' => $sell_order['row_id'],
                                        'cBatch'=>$sk_arr[1],
                                        'shelves_id' => $sk_arr[2],
                                        'fqty' => $thisqty,
                                        'fauxqty' => $thisqty/$sell_order['fCoefficient'],
                                        'inv_number' =>$sell_order['inventory_number'],
                                        'qrNo' => isset($qrNo_arr[$sk_arr[0].'_'.$sk_arr[1]])?$qrNo_arr[$sk_arr[0].'_'.$sk_arr[1]]:''
                                    ];
                                }
                            }
                        }
                    }

                    if($total_fqty<=0){
                        continue;
                    }
                }
            }
            //按行号排序
            array_multisort(array_column($deal_data, 'row_id'),SORT_ASC,$deal_data);
            //重新赋值表体
            $detail = $deal_data;
        }
        
        //明细
        foreach ($detail as $k=>$v){
            //添加临时处理表
            $shelves_number = '';
            if($type != 8){//调拨，有可能原货架为空
                // 处理组装单
                if($type == 16 && $v['b_remark']=='母件'){
                    $warehouseId = $main['to_stock_id'];//母件进入仓库
                }else{
                    $warehouseId = $main['stock_id'];//子件进入仓库
                }

                $get_shelves = db('shelves')->where([
                    'id'=>$v['shelves_id'],
                    'warehouse_id'=>$warehouseId])
                    ->field('type,number')
                    ->find();

                    if(!$get_shelves){
                        exception('找不到对应库区编码,库区ID['.$v['shelves_id'].']');
                    }
                    
                    $shelves_number = $get_shelves['number'];
                    $v['shelves_type'] = $get_shelves['type'];
            }
            $inv_number = $v['inv_number'];
            if($type == 8){
                //调拨数量转换
                $v['fqty'] = $main['totalnum'];
                $v['allot_inv_number'] = $v['inv_number'];
                $v['allot_shelves_id'] = $v['shelves_id'];
                $v['allot_to_shelves_id'] = $v['to_shelves_id'];
                
                $v['shelves_id'] = $v['to_shelves_id'];//把目标库区，写入表头，方便获取账套编码
                $v['inv_number'] = '';
                $v['shelves_type'] = '';
            }
            if($type == 9){
                //盘点数量转换
                $v['fqty'] = $main['totalnum'];
                $v['check_inv_number'] = $v['inv_number'];
                $v['check_shelves_id'] = $v['shelves_id'];
                
                $v['inv_number'] = '';
                $v['shelves_type'] = '';
                $v['shelves_id'] = '';
            }

            //20241222新增销售方式，0没有，1内销，2外销，针对调味包，默认1
            $sell_in_out = 0;
            if($type == 14&&isset($main['source_code'])){
                /*if($main['source_code']&&stripos($main['source_code'],'WORK')===0){
                    //原味橄榄菜配料包	
                    $sell_in_out = 1;
                }*/
                $sell_in_out = 1; //默认否
            }
            
            $shelves_type = 0;//货架类型 1库区 2货架
            if(isset($v['shelves_type'])){
                $shelves_type = $v['shelves_type'];
            }
            
            //如果没启用批号，则抹去批号
            $inventory_arr = db('inventory')
            ->where('number',$inv_number)
            ->field('id,mbatch')
            ->find();
            if(!$inventory_arr['mbatch']){
                $v['cBatch'] = '';//当物料没启用批号时，去掉提交上来的批号
            }

            $temporary =   [
                'auto_id'=>isset($v['auto_id'])?$v['auto_id']:0,//针对有u8源单的，放明细id
                'source_code'=>isset($main['source_code'])?$main['source_code']:'',
                'order_code'=>$code,
                'order_date'=>$main['FDate'],
                'order_list'=>$type,
                'inv_id' => $inventory_arr['id'],
                'number'=>$v['inv_number'],
                'row_id'=>isset($v['row_id'])?$v['row_id']:0,
                //'warehouse_code'=>$warehouse_number,
                'warehouse_id'=>$warehouseId,
                'shelves_code'=>@$shelves_number,
                'shelves_id'=>$v['shelves_id'],
                'shelves_type'=>$shelves_type,
                'quantity'=>$v['fqty'],
                'store_quantity'=>(isset($v['fauxqty'])&&$v['fauxqty'])?$v['fauxqty']:$v['fqty'],
                'cBatch'=>isset($v['cBatch'])?$v['cBatch']:'',//批号
                'status' => $status,
                'grounding_list'=>$shelves_type==2?'1':'0',//是否上架
                'createtime'=>date('Y-m-d H:i:s'),
                'remark' => $remark,
                'b_remark' => isset($v['b_remark'])?$v['b_remark']:'',
                'qrNo' => isset($v['qrNo'])?$v['qrNo']:'',
                'u8userid' => $main['userid'],//变成wms用户，回写再去取kis用户
                'u8username' => $main['username'],//变成wms用户，回写再去取kis用户
                'cDepCode' => isset($main['factory_code'])?$main['factory_code']:'',//kis领料单专用，部门id
                'cDepName' => isset($main['factory_name'])?$main['factory_name']:'',//kis领料单专用，部门名称
                'sell_in_out' => $sell_in_out
            ];
            
            if($type==8||$type==9){
                if($k==0){
                    $temporary['id'] = db('temporary')->insertGetId($temporary);
                    $temporary_id = $temporary['id'];
                }
            }else{
                $temporary['id'] = db('temporary')->insertGetId($temporary);
            }
            
            //插入表体(其他入、出库单、盘点、调拨)
            switch ($type){
                case 1: //采购入库
                case 14://产品入库
                    if (!$v['shelves_id']) exception('库区不能为空');
                    
                    //更新采购数量 , 应该只更新这条
                    $procure = new Procure;
                    $procure->updateProducedata($main['source_code'],$v['auto_id']);
                    break;
                case 2://生产任务 材料清单出库
                    if (!$v['shelves_id']) {
                        exception('库区不能为空');
                    }
                    if (!$v['b_remark']) {
                        //判断拣货单单号不能为空，引拣货单源单
                        exception('源单编码为空');
                    }
                    break;
                case 5:
                case 6:
                case 7:
                case 10:
                case 11:
                    if (!$v['shelves_id']) {
                        exception('库区不能为空');
                    }
                    break;
                case 3:
                    $list = [
                        'code' => $code,
                        'shelves_id' => $v['shelves_id'],
                        'row_id' => $v['row_id'],
                        'cInvCode' => $v['inv_number'],
                        'iQuantity' => $v['fqty'],
                        'createtime' => date('Y-m-d H:i:s'),
                    ];
                    //表体
                    db('rdinrecord_list')->insert($list);
                    break;
                case 4:
                    $list = [
                        'code' => $code,
                        'shelves_id' => $v['shelves_id'],
                        'row_id' => $v['row_id'],
                        'cInvCode' => $v['inv_number'],
                        'iQuantity' => $v['fqty'],
                        'createtime' => date('Y-m-d H:i:s'),
                    ];
                    //表体
                    db('rdoutrecord_list')->insert($list);
                    break;
                case 8:
                    // if($db_type == 2){
                    //     //异库，检查接收仓库，是否存在那个货架编码
                    //     $to_shelves_id = db('shelves')->where([
                    //         'warehouse_id' => $to_warehouseId,
                    //         'id' =>$v['allot_to_shelves_id']
                    //     ])->value('id');
                    //     if(!$to_shelves_id){
                    //         exception("目标仓库ID:{$to_warehouseId},库区{$v['to_shelves_name']}不存在");
                    //     }
                    // }
                    //调拨逻辑
                    $tpdjList = [
                        'code'=>$code,
                        'kc_id'=>$v['kc_id'],
                        "inv_id" => $v['inv_id'],
                        'shelves_id'=>$v['allot_shelves_id'],
                        'shelves_change_id'=>$v['allot_to_shelves_id'],
                        'cInvCode'=>$v['allot_inv_number'],
                        'tp_iQuantity'=>$v['allot_qty'],
                        'store_quantity'=>$v['allot_auxqty'],
                        'cBatch' => $v['cBatch'],
                        'createtime'=>date('Y-m-d H:i:s')
                    ];
                    
                    //再次判断即时库存
                    $check_kc_qty = db('wms_kc')->where('id',$v['kc_id'])->value('quantity');
                    if($check_kc_qty<$v['allot_qty']){
                        exception('物料'.$v['inv_name'].',库存不足');
                    }
                    if(!$v['allot_to_shelves_id']){
                        exception('物料'.$v['inv_name'].'-'.$v['cBatch'].',目标路径为空');
                    }
                    
                    //添加调拨单货物列表
                    Db::name('tpdj_list')->insert($tpdjList);
                    break;
                case 9:
                    //盘点，盘盈盘损,先做记录，不处理库存，在pc端处理
                    $pc_check_kc = db('check_vouch')->where([
                    'code' => $main['source_code'],
                    'status' => 1
                    ])
                    ->find();
                    if(!$pc_check_kc){
                        exception("盘点任务编号{$main['source_code']}不存在或已被删除");
                    }
                    
                    $iAdInQuantity = 0;//其他入数量
                    $iAdOutQuantity = 0;//其他出数量
                    
                    //再次获取即时库存，判断传过来的库存数是否一致，不一致，则提示
                    /* $kc_qty = Wmskc::getKcQty($warehouseId , $v['check_shelves_id'], $v['check_inv_number']);
                     if($kc_qty!=$v['kc_qty']){
                     exception("物料 {$v['check_inv_number']}库存[{$kc_qty}]和PDA账面库存不一致,请同步最新库存");
                     }  */
                    //pda库存作为扫描即时库存
                    $kc_qty = $v['kc_qty'];//pda库存数
                    $checkItmeModel = CheckVouchList::where([
                        'code' => $main['source_code'],
                        'cInvCode' => $v['check_inv_number'],
                        'cBatch' => $v['cBatch'],
                        'shelves_id' => $v['check_shelves_id']//货架是本地的数据，id是自增的，所以，虽然不同仓库，但货架id是唯一的
                    ])
                    ->find();
                    
                    if($kc_qty>$v['check_qty']){
                        //盘亏 出库
                        $iAdOutQuantity = round($kc_qty-$v['check_qty'],$digits);
                    }else{
                        //盘盈
                        $iAdInQuantity = round($v['check_qty']-$kc_qty,$digits);
                    }
                    
                    if($checkItmeModel){
                        //没扫描过，才进行处理   有扫描的跳过
                        //if(!$checkItmeModel->scan_flag){
                        $checkItmeModel->scan_flag = 1;
                        $checkItmeModel->kc_quantity = $v['kc_qty'];
                        $checkItmeModel->kc_store_quantity = $v['kc_auxqty'];
                        $checkItmeModel->scantime = $v['scan_datetime'];
                        $checkItmeModel->iAdInQuantity = $iAdInQuantity;
                        $checkItmeModel->iAdOutQuantity = $iAdOutQuantity;
                        $checkItmeModel->iCVCQuantity = $v['check_qty'];
                        $checkItmeModel->store_quantity = $v['check_auxqty'];
                        $checkItmeModel->temporary_id = $temporary_id;
                        $checkItmeModel->save();
                        //}
                    }else{
                        $checkList = [
                            'code' => $main['source_code'],
                            'iQuantity' => $kc_qty,
                            'kc_store_quantity' => $v['kc_auxqty'],
                            'kc_quantity' => $kc_qty,
                            'inv_id' => $v['inv_id'],
                            'inv_name' => $v['inv_name'],
                            'cBatch' => $v['cBatch'],
                            'cInvCode' => $v['check_inv_number'],
                            'iAdInQuantity' => $iAdInQuantity,
                            'iAdOutQuantity' => $iAdOutQuantity,
                            'iCVCQuantity' => $v['check_qty'],
                            'store_quantity' => $v['check_auxqty'],
                            'shelves_id' => $v['check_shelves_id'],
                            'shelves_name' => $v['shelves_name'],
                            'scantime' => $v['scan_datetime'],
                            'createtime' => date('Y-m-d H:i:s'),
                            'scan_flag' => 1,
                            'temporary_id' => $temporary_id
                        ];
                        //盘点表体
                        Db::name('check_vouch_list')->insert($checkList);
                    }
                    break;
                case 12:
                    //拣货
                    // if (!$main['to_shelves_id']) {
                    //     exception('暂存区不能为空');
                    // }
                    if (!$v['shelves_id']) {
                        exception($v['inv_number'].'库区不能为空');
                    }
                    //再次判断即时库存
                    $kc_qty = db('wms_kc')->where([
                        'warehouse_id'=>$main['stock_id'],
                        'inv_number'=>$v['inv_number'],
                        'shelves_id'=>$v['shelves_id']
                        
                    ])->value('quantity');
                    if($kc_qty<$v['fqty']){
                        exception($v['inv_name'].'选择路径,库存不足');
                    }
                    
                    //更新出库任务数量
                    $material = new Material();
                    $material->getMaterialData($main['source_code']);
                    break;
                case 15:
                    //销售出库
                    if (!$v['shelves_id']) {
                        exception('库区不能为空');
                    }
                    //更新出库数量 , 应该只更新这条
                    $material = new Material();
                    $material->getMaterialData($main['source_code'],$v['auto_id']);
                    break;
            }
            //保存进数组，批量新增
            $temp_arr[] = $temporary;
        }
        
        //是否自动处理数据1是，0否
        if($status){
            $this->dealTempData( $temp_arr, $type);
        }
    }
    
    //处理临时表数据
    /* 1、更新采购单数量
     * 2、更新本地库存
     * 3、插入中间库
     * $temp_arr 临时表明细， $type 单据类型
     * $repeatKis 是否重新发起回写金蝶操作，不更新本地库存
     *   */
    public function dealTempData($temp_arr,$type,$repeatKis = false){
        //出入库类型:1=收货,12=拣货,2=领料出库,3=其他入库,4=其他出库,5=源单上架，6=采购退回 
        //7领料退回 8调拨 9盘点10直接上架11直接领料  14产品入库 15销售出库
        try{
            if(!$temp_arr){
                exception('pda单据表体参数有误');
            }
            
            //默认小数位数
            $digits = getDigits();
            $u8Head = [];//表头
            $u8Items = [];//表体
            $procureDetail = [];//金蝶采购订单详细
            $seoutDetail = [];//金蝶发货通知单详细
            $adminArr = session('admin');
            $stocker_id = 0;//金蝶对应仓库，仓管人
            $order_code = 0;//pda单据号
            $warehouse_change_id = 0;//调拨目标仓id

            foreach($temp_arr as $k=>$v){
                $warehouseId = $v['warehouse_id'];
                $code = $v['order_code'];
                $order_date = $v['order_date'];
                $now = date('Y-m-d H:i:s');

                $kcData = [
                    'code'=>$code,
                    'code_date'=>$order_date,
                    'inv_number'=>$v['number'],
                    'cBatch' => isset($v['cBatch'])?$v['cBatch']:'',
                    'quantity'=>$v['quantity'],
                    'warehouse_id'=>$warehouseId,
                    'shelves_id'=>$v['shelves_id']
                ];

                if($k==0){
                    //得到金蝶表头
                    $order_code = $v['order_code'];//下面更新kis单据号用到
                    if($type==8){
                        $warehouse_change_id = db('tpdj')->where('code',$code)->value('warehouse_change_id');
                        $v['warehouse_change_id'] = $warehouse_change_id;
                    }
                    
                    $u8Head = $this->erpTableHead($v,$type);
                    if($type==9){
                        //盘点,初始化kis表体
                        $u8Items['IN'] = [];
                        $u8Items['OUT'] = [];
                    }
                }

                //===============判断 入库源单，判断
                if($type==1||$type==14){
                    //本地采购入库任务
                    $procureDetail = Procure::where([
                        'warehousing_code' => $v['source_code'],
                        'auto_id' => $v['auto_id']
                    ])
                    ->find();
                    if(!$procureDetail){
                        exception('暂时找不到对应入库任务,请稍后再试');
                    }
                    
                    //再次核实金蝶，入库任务（采购订单、生产任务单）是否存在
                    if($procureDetail['FInterID']&&$procureDetail['type']!=1){
                        if($procureDetail['type']==0){
                            $procureKisDetail = Kisapi::getDataByName('procureDetail',['fInterId'=>$procureDetail['FInterID']]);
                        }else{
                            $procureKisDetail = Kisapi::getDataByName('getIcmoList',['fbillno'=>$procureDetail['warehousing_code']],true);
                            $procureKisDetail = $procureKisDetail['data_item'][0];
                        }
                        if(!$procureKisDetail){
                            exception('金蝶单据：'.$procureDetail['warehousing_code'].'不存在');
                        }
                    }
                    // if($type==1&&!$v['pass_status']){
                    //     exception('该单据未质检通过,请先质检');
                    // }
                }

                if($type==15){
                    //本地出库任务
                    $seoutDetail = MaterialListView::where([
                        'material_code' => $v['source_code'],
                        'auto_id' => $v['auto_id']
                    ])
                    ->find();
                    if(!$seoutDetail){
                        exception('暂时找不到对应出库任务,请稍后再试');
                    }
                }
                
                //===============判断
                switch ($type){
                    case 1:
                        //金蝶表体  pda质检过写金蝶
                        if($v['pass_status']){
                            //20240323质检通过，才写本地库存和回写金蝶
                            Wmskc::OperateWmsKc($kcData, 'inc', $type,'采购入库增库存',$repeatKis);
                            $u8Items[] = $this->erpTableBodyCommon($v,1,$procureDetail);
                        }else{
                            //更新本地库存   wms平台复核  不写金蝶
                            //Wmskc::OperateWmsKc($kcData, 'inc', $type,'采购入库增库存',$repeatKis);
                            //240326单纯更新status=1状态了
                        }
                        break;
                    case 3:
                        //金蝶通用表体
                        $u8Items[] = $this->erpTableBodyCommon($v,$type);
                        //更新本地库存
                        Wmskc::OperateWmsKc($kcData, 'inc', $type,'其他入库加库存',$repeatKis);
                        break;
                    case 4:
                        //金蝶通用表体
                        $v['b_remark'] = $v['remark'];//其他出库单，把表头的备注写入表体
                        $u8Items[] = $this->erpTableBodyCommon($v,$type);
                        //更新本地库存
                        Wmskc::OperateWmsKc($kcData, 'dec', $type,'其他出库减库存',$repeatKis);
                        break;
                    case 6://采购退回
                        //金蝶表体
                        $u8Items[] = $this->erpTableBodyCommon($v,$type);
                        //减本地
                        Wmskc::OperateWmsKc($kcData, 'dec', 6,'采购退回减库存',$repeatKis);
                        break;
                    case 7://领料退回，表体字段b_remark有注明，良品的（不回写到u8）新品才要
                        //加本地
                        Wmskc::OperateWmsKc($kcData, 'inc', 7,'领料退回加库存'.$v['b_remark'],$repeatKis);//b_remark新品 良品
                        //新增一条记录进中间库，更新u8
                        $shelves_wh_type = db('shelves')->where('id',$v['shelves_id'])->value('wh_type');
                        if($shelves_wh_type==2||$v['b_remark']=='良品'){
                            //代管仓 不回写到u8 这里不加入表体明细 下面调u8api，就不会回写
                        }else{
                            //金蝶通用表体
                            $u8Items[] = $this->erpTableBodyCommon($v,$type);
                        }
                        break;
                    case 8:
                        $tpdj = db('tpdj')->where('code',$code)->find();
                        if(!$tpdj){
                            exception('不存在调拨记录');
                        }
                        
                        if($tpdj['status']&&!$repeatKis){
                            exception('该调拨记录已被处理');
                        }
                        
                        $tpdj_details = db('tpdj_list')->where('code',$code)->select();
                        if(!$tpdj_details){
                            exception('调拨明细为空');
                        }
                        
                        foreach($tpdj_details as $k=>$tpdj_detail){
                            //获取物料详细
                            $inventory_arr = db('inventory')
                            ->where('id',$tpdj_detail['inv_id'])
                            ->field('name inv_name,unit,unit_code,store_unit,store_unit_code,fCoefficient')
                            ->find();

                            $tpdj_detail = array_merge($inventory_arr,$tpdj_detail);
                            
                            $tpdj_detail['quantity'] = $tpdj_detail['tp_iQuantity'];
                            $tpdj_detail['b_remark'] = '';
                            $tpdj_detail['warehouse_id'] = $warehouseId;
                            $tpdj_detail['warehouse_change_id'] = $warehouse_change_id;
                            //金蝶通用表体,源仓库id和目标仓库id，相同，不加入
                            $tempItem = $this->erpTableBodyCommon($tpdj_detail,$type);
                            if($tempItem){
                                $u8Items[] = $tempItem;
                            }

                            //先减原货架记录,再新增
                            $data = [
                                'code'=>$code,
                                'code_date'=>$order_date,
                                'inv_number'=>$tpdj_detail['cInvCode'],
                                'quantity'=>$tpdj_detail['tp_iQuantity'],
                                'warehouse_id' => $tpdj['warehouse_id'],
                                'shelves_id' => $tpdj_detail['shelves_id'],
                                'warehouse_change_id' => $tpdj['warehouse_change_id'],
                                'shelves_change_id' => $tpdj_detail['shelves_change_id'],
                                'cBatch' => $tpdj_detail['cBatch'],
                                'kc_id' => $tpdj_detail['kc_id']
                            ];
                            Wmskc::tbdjUpdataKc($data,$repeatKis);
                        }
                        
                        db('tpdj')->where('code',$code)->update(['status'=>1]);
                        Log::log($code . ':pda调拨单据处理');
                        break;
                    case 9://盘点
                        $vouch = db('check_vouch')->where('code',$v['source_code'])->find();
                        if(!$vouch){
                            exception('不存在盘点记录');
                        }
                        if($vouch['status']==0){//||$vouch['status']==2
                            exception('该盘点记录已被关闭');
                        }
                        
                        $vouch_details = db('check_vouch_list')->where([
                            'code' => $v['source_code'],
                            //'temporary_id'=>$v['id'],
                            'a.deletetime'=>null,//没被一键清除的
                            //'scantime' => ['neq','not null'] //扫描时间不为空
                        ])->alias('a')
                        ->join('inventory b','a.inv_id=b.id','left')
                        ->field('a.*,b.unit,b.unit_code')
                        ->select();
                        
                        if(!$vouch_details){
                            exception("盘点单号{$v['source_code']},扫描明细为空");
                        }
                        
                        //先更新即时库存，期间入，期间出
                        $new_vouch_details = [];
                        foreach($vouch_details as $k=>$vouch_detail){
                            //获取物料详细
                            $inventory = db('inventory')
                            ->where('id',$vouch_detail['inv_id'])
                            ->field('unit,unit_code,store_unit,store_unit_code')
                            ->find();
                            
                            $kc_qty = db('wmskc')->where([
                                'inv_number' => $vouch_detail['cInvCode'],
                                'warehouse_id' => $warehouseId,
                                'shelves_id' => $vouch_detail['shelves_id'],
                                'cBatch' => $vouch_detail['cBatch']
                            ])
                            ->sum('quantity');
                            $vouch_detail['kc_quantity'] = $kc_qty;//即时库存
                            $vouch_detail['duringIn'] = 0;
                            $vouch_detail['duringOut'] = 0;
                            $vouch_detail['iAdInQuantity'] = 0;//初始化盘盈0
                            $vouch_detail['iAdOutQuantity'] = 0;//初始化盘亏0
                            $vouch_detail['warehouse_id'] = $warehouseId;
                            $vouch_detail['unit'] = $inventory['unit'];
                            $vouch_detail['unit_code'] = $inventory['unit_code'];
                            $vouch_detail['store_unit'] = $inventory['store_unit'];
                            $vouch_detail['store_unit_code'] = $inventory['store_unit_code'];
                            
                            if($vouch_detail['scantime']){//扫描时间不为空
                                //得到期间入和出
                                $duringInOutArr = Kcmx::getKcmxQtyByDuringDate($warehouseId, $vouch_detail['shelves_id'],$vouch_detail['cInvCode'],$vouch_detail['scantime']);
                                $vouch_detail['duringIn'] = $duringInOutArr['in'];
                                $vouch_detail['duringOut'] = $duringInOutArr['out'];
                            
                                //盘点+（期间入-期间出） - 即时库存  大于0的，针对期初出库的计算（按期初是0即时库存 - （盘点数+期间入-出）理解）
                                $duringQuantity = round($kc_qty - ($vouch_detail['iCVCQuantity']+$duringInOutArr['sy']),$digits);
                                if($duringQuantity<0){
                                    //其他入
                                    $vouch_detail['iAdInQuantity'] = abs($duringQuantity);
                                    $vouch_detail['iAdOutQuantity'] = 0;
                                    $u8Items['IN'][] = $this->erpTableBodyCommon($vouch_detail,$type);
                                }
                                if($duringQuantity>0){
                                    //其他出
                                    $vouch_detail['iAdInQuantity'] = 0;
                                    $vouch_detail['iAdOutQuantity'] = $duringQuantity;
                                    $u8Items['OUT'][] = $this->erpTableBodyCommon($vouch_detail,$type);
                                }
                            }else{
                                //扫描时间为空，库存数，以其他出形式出掉,但有库存
                                if($kc_qty){
                                    $vouch_detail['iAdInQuantity'] = 0;
                                    $vouch_detail['iAdOutQuantity'] = $kc_qty;
                                    $u8Items['OUT'][] = $this->erpTableBodyCommon($vouch_detail,$type);
                                }
                            }
                            
                            //更新
                            $obj = new CheckVouchList();
                            //db('check_vouch_list')->where('id',$vouch_detail['id'])->update($vouch_detail);
                            $obj->allowField(true)->save($vouch_detail,[
                                'id' => $vouch_detail['id']
                            ]);

                            $new_vouch_details[] = $vouch_detail;
                        }
                        
                        $vouch_details = $new_vouch_details;
                        foreach($vouch_details as $k=>$vouch_detail){//$new_vouch_details
                            $data = [
                                'code'=>$code,
                                'code_date'=>$order_date,
                                'inv_number'=>$vouch_detail['cInvCode'],
                                'cBatch'=>$vouch_detail['cBatch'],
                                'warehouse_id' => $warehouseId,
                                'shelves_id' => $vouch_detail['shelves_id']
                            ];
                            Log::info($vouch_detail,'pda盘点单据(期间出、入)数据');
                            //盘亏其他出库，盘盈其他入库
                            if($vouch_detail['iAdInQuantity']>0){
                                //盘盈其他入库
                                //加本地
                                $data['quantity'] = $vouch_detail['iAdInQuantity'];
                                Wmskc::OperateWmsKc($data,'inc',3,"盘盈入库，盘点单号：{$code}",$repeatKis);
                            }
                            if($vouch_detail['iAdOutQuantity']>0){
                                //盘亏其他出库
                                //减本地
                                $data['quantity'] = $vouch_detail['iAdOutQuantity'];
                                Wmskc::OperateWmsKc($data,'dec',4,"盘亏出库，盘点单号：{$code}",$repeatKis);
                            }
                        }
                        
                        //复核后，关闭盘点单
                        db('check_vouch')->where('code',$code)->update(['status'=>2]);
                        Log::log($code . ':pda盘点单据处理');
                        break;
                    case 10:
                        //直接上架，2种情况（库存无货架、新物料入库）
                        break;
                    case 11:
                        //通用表体明细
                        $u8Items[] = $this->erpTableBodyCommon($v,$type);

                        //直接领料，直接减库存
                        Wmskc::OperateWmsKc($kcData, 'dec', 11,'直接领料，直接减库存，'.$v['b_remark'],$repeatKis);
                        break;
                    case 12://拣货，读源单拣货任务，出库
                        break;
                    case 14://产品入库
                        if($procureDetail['type']==1){//mes外包入库
                            //已质检
                            //更新本地库存
                            $kcData['warehouse_id'] = 7676;//成品仓
                            $kcData['shelves_id'] = 1;//待检区
                            Wmskc::OperateWmsKc($kcData, 'dec', $type,'移库外包产品入库减库存',$repeatKis);
                            
                            //更新本地库存
                            $kcData['warehouse_id'] = 7676;//成品仓
                            $kcData['shelves_id'] = 3;//成品区
                            Wmskc::OperateWmsKc($kcData, 'inc', $type,'移库外包产品入库增库存',$repeatKis);

                            //金蝶表体
                            $u8Items[] = $this->erpTableBodyCommon($v,$type,$procureDetail);
                            
                            // if(!$v['sell_in_out']){
                            //     $this->error("请先设置销售方式");
                            // }

                            //这里不回写金蝶
                        }else if($procureDetail['type']==2){//生产任务单入库
                            //金蝶表体
                            $u8Items[] = $this->erpTableBodyCommon($v,$type,$procureDetail);
                            //更新本地库存
                            Wmskc::OperateWmsKc($kcData, 'inc', $type,'生产任务产品入库增库存',$repeatKis);
                        }
                        break;
                    case 15://销售出库
                        //金蝶表体
                        $u8Items[] = $this->erpTableBodyCommon($v,15,$seoutDetail);

                        Wmskc::OperateWmsKc($kcData, 'dec', $type,'销售出库减库存',$repeatKis);
                        break;
                    case 16://组装单
                        //1、拼好组装单明细
                        //2、拼其他出入明细
                        //3、拼其他入库明细
                        $u8Items[] = $this->erpTableBodyCommon($v,16);
                        if($v['b_remark']=='母件'){//加
                            Wmskc::OperateWmsKc($kcData, 'inc', $type,'组装单加库存',$repeatKis);
                            $u8Items['IN'][] = $this->erpTableBodyCommon($v,16);
                        }else if($v['b_remark']=='子件'){//减
                            Wmskc::OperateWmsKc($kcData, 'dec', $type,'组装单减库存',$repeatKis);
                            $u8Items['OUT'][] = $this->erpTableBodyCommon($v,16);
                        }
                        break;
                }
            }
            
            //循环后，调API,回写数据到金蝶
            $backu8 = config('site.backu8');
            if($backu8){
                if($type){
                    //回写相关
                    // if((!$u8Head||!$u8Items)){
                    //     exception('回写KIS参数表头、表体为空');
                    // }
                    $res = [];
                    $dbres = [];//生成任务-产品入库时的调拨
                    switch ($type){//调API回写U8 
                        case 1://采购入库 
                        case 6://采购退回
                            if($u8Items){
                                $u8Head['ics01Detail'] = $u8Items;
                                $res = Kisapi::kiscurl('/api/wms/savePurOrder',$u8Head);
                            }
                            break;
                        case 14://产品入库
                            if($u8Items){
                                if($procureDetail['type']==1){
                                    //$u8Head['fdept'] = 10395;//外包车间
                                    //20241220 动态取车间
                                    $u8Head['fdept'] = $procureDetail['factory_code'];
                                    //20251022 动态取入库日期
                                    $u8Head['fdt'] = $procureDetail['order_date'];
                                }
                                //生成任务，产品入库，技术部PDA入库时，配料包的入库、添加剂的入库、
                                //配料包的调拨，添加剂和味精的出库，这四类单据的日期，与生产任务单的计划开工日期一致、
                                if($procureDetail['type']==2){
                                    $u8Head['fdt'] = $procureDetail['warehousing_date'];
                                }

                                $u8Head['ics02Detail'] = $u8Items;
                                $res = Kisapi::kiscurl('/api/wms/saveStockRm',$u8Head);
                                
                                if($procureDetail['type']==2){

                                    //判断是否生产任务单，是，生成材料出库单, 返回调料包数组
                                    $tiaoliaobao_arr = self::kisMaterialOut($u8Head,$v,true);
                                    
                                    //半成品入库后，调拨到熬煮车间
                                    unset($u8Head['ics02Detail']);//去掉上一个的明细
                                    foreach($u8Items as &$u8Item){
                                        $u8Item['fSCStockID'] = $u8Item['fDCStockID'];
                                        $u8Item['fDCStockID'] = 10386;
                                    }
                                    $u8Head['ics41Detail'] = $u8Items;
                                    $dbres = Kisapi::kiscurl('/api/wms/saveTransVouch',$u8Head);
                                }
                            }
                            break;
                        case 2://领料出库
                            break;
                        case 3://其他入库
                            $u8Head['ics10Detail'] = $u8Items;
                            $res = Kisapi::kiscurl('/api/wms/saveOtherInAdd',$u8Head);
                            break;
                        case 4://其他出库
                            $u8Head['ics29Detail'] = $u8Items;
                            $res = Kisapi::kiscurl('/api/wms/saveOtherOutAdd',$u8Head);
                            break;
                        case 7: //领料退回
                        case 11://直接领料
                            $u8Head['ics24Detail'] = $u8Items;
                            $res = Kisapi::kiscurl('/api/wms/saveMaterialOut',$u8Head);
                            break;
                        case 9://盘点
                            $cCode = [];
                            if(count($u8Items['IN'])>0){
                                $u8Head['ics10Detail'] = $u8Items['IN'];
                                $res_in = Kisapi::kiscurl('/api/wms/saveOtherInAdd',$u8Head);
                                $cCode[] = $res_in['cCode'];
                            }
                            
                            if(count($u8Items['OUT'])>0){
                                unset($u8Head['ics10Detail']);//去掉上面
                                $u8Head['ics29Detail'] = $u8Items['OUT'];
                                $res_out = Kisapi::kiscurl('/api/wms/saveOtherOutAdd',$u8Head);
                                $cCode[] = $res_out['cCode'];
                            }
                            
                            if($cCode){
                                $res['cCode'] = implode(',',$cCode);
                            }
                            break;
                        case 8://调拨
                            if($u8Items){
                                $tpdj = db('tpdj')->where('code',$code)->find();
                                $u8Head['fReqNumber'] = $tpdj['material_code']??'';
                                $u8Head['ics41Detail'] = $u8Items;
                                $res = Kisapi::kiscurl('/api/wms/saveTransVouch',$u8Head);
                            }
                            break;
                        case 15://销售出库
                            if(config('site.syn_kis_sellout_flag')){
                                $u8Head['ics21Detail'] = $u8Items;
                                $res = Kisapi::kiscurl('/api/wms/saveSaleOut2',$u8Head);
                            }
                            break;
                        case 16://组件单
                            $in_arr = $u8Items['IN'];
                            $out_arr = $u8Items['OUT'];
                            unset($u8Items['IN'],$u8Items['OUT']);//去掉

                            $u8Head['icsChangeDetail'] = $u8Items;//组装单
                            $res = Kisapi::kiscurl('/api/wms/saveIcchange',$u8Head);
                            break;
                    }
                    
                    if ($res){
                        $temporaryModel = new Temporary();
                        if($type==16){
                            //cCode=组装单号,其他出库单,其他入库单
                            $code_arr = explode(',',$res['cCode']);
                            $res['cCode'] = $code_arr[0];//组装单号
                            $res_out['cCode'] = isset($code_arr[1])?$code_arr[1]:'';//其他出
                            $dbres['cCode'] = isset($code_arr[2])?$code_arr[2]:'';//其他入
                        }

                        //更新pda金蝶单据编号
                        $update_code = [
                            'u8_code' => $res['cCode'],
                            'kis_dbcode' => isset($dbres['cCode'])?$dbres['cCode']:null,//调拨、组装的其他入
                        ];
                        if($type==16){
                            $update_code['kis_work_outcode'] = isset($res_out['cCode'])?$res_out['cCode']:null; //组装的其他出
                        }
                        $temporaryModel->save($update_code,[
                            'order_code'=>$order_code
                        ]);
                    }
                }
            }
        }catch (\Exception $e){
            Log::error($order_code.'错误：'.$e->getMessage().PHP_EOL.$e->getTraceAsString());
            exception($e->getMessage());
        }
    }

    // 获得KIS回写表头
    public function erpTableHead($v,$order_type = 0){
        $u8Head = [];
        $backu8 = config('site.backu8');
        if(!$backu8){
            return $u8Head;
        }

        $adminArr = session('admin');
        $warehouseId = $v['warehouse_id'];
        $stocker_id = db('warehouse')->where('id',$warehouseId)->value('stocker_id');//仓管
        $adminDb = db('admin')->where('username',$v['u8username'])->field('u8_handler_id,u8_user_id')->find();
        $frob = 1;
        $fdept = isset($v['cDepCode'])?$v['cDepCode']:0;//部门;
        $femp = 0;

        //得到转换后的erp仓库id
        $erp_warehouse_id = Shelves::getErpWarehouseId($v);
        if($erp_warehouse_id){
            $warehouseId = $erp_warehouse_id;
        }
        
        //如果0则用默认配置
        if(!$fdept&&config('site.kis_common_dpt_id')){
            $fdept = config('site.kis_common_dpt_id');
        }

        if(config('site.kis_common_emp_id')){
            $femp = config('site.kis_common_emp_id');
        }

        //调拨单，仓管取调入仓库的
        if($order_type==8){
            $stocker_id = db('warehouse')->where('id',$v['warehouse_change_id'])->value('stocker_id');//仓管
        }
        
        //通用表头数组
        $u8Head = [
            "fdept" => $fdept,//部门id, 其他出、入、组装单 部门必填  
            "fsup" => 0,
            "femp" =>  $femp,
            "fstockid" => $warehouseId,
            "fbillNo" =>  $v['order_code'],//pda单号
            "fdt" =>  $v['order_date'],
            "frob" => 1,
            "fExplanation" => $v['remark'],
            "fUse" => $v['remark'],
            "fFManagerID" => $stocker_id,
            "fSManagerID" => $stocker_id,
            "fstatus" => 1,//默认审核
            "fChecker" => $adminDb['u8_handler_id'],//审核人
            "fuser" => isset($adminDb['u8_user_id'])?$adminDb['u8_user_id']:'',//创建人
            'fAcctNum' => Shelves::getErpAccNum(isset($v['shelves_id'])?$v['shelves_id']:0,$order_type)
        ];

        //领料退回、盘点、直接出库
        if($order_type==6||$order_type==7){
            $u8Head['frob'] = -1;
            $u8Head['fsup'] = isset($v['cDepCode'])?$v['cDepCode']:0;//供应商
        }

        //金蝶外购入库单
        if($order_type == 1){
            $kisProcureDetail = Kisapi::getDataByName('procureDetail',['fbillNo'=>$v['source_code']]);
            if(!isset($kisProcureDetail['fDeptId'])){
                exception('找不到金蝶源单数据');
            }
            $temp = [
                "fdept" => $kisProcureDetail['fDeptId'],//部门id,
                "fsup" => $kisProcureDetail['fSupplyId'],
                "femp" =>  $kisProcureDetail['fEmpId'], 
            ];
            $u8Head = array_merge($u8Head,$temp);
        }

        //金蝶销售出库
        if($order_type == 15){
            //取味业金蝶，销售出库单
            $u8Head['fbillNo'] = $v['source_code'];//销售出库单号
            $u8Head['wmsbillno'] = $v['order_code'];//wms单号
        }

        //20241223
        if($order_type == 14){
            //产品入库新增，是否自营出口，1否，2是
            $u8Head['saleType'] = $v['sell_in_out']==2?1:0;
        }

        return $u8Head;
    }

    // 获得KIS回写通用表体 
    public function erpTableBodyCommon($v,$order_type = 0,$procureDetail = []){
        $warehouseId = $v['warehouse_id'];

        if($order_type==9){//盘点
            if($v['iAdInQuantity']>0){
                //其他入
                $v['quantity'] = $v['iAdInQuantity'];
            }
            if($v['iAdOutQuantity']>0){
                //其他出
                $v['quantity'] = $v['iAdInQuantity'];
            }
            $v['b_remark'] = '';
        }
        
        $comm_arr = [
            "fitemId" => $v['inv_id'],
            "fitemNm" => $v['inv_name'],//物料名称
            "fqty" => $v['quantity'],
            "fBatchNo" => $v['cBatch'],
            //"fUnitID" => $v['unit_code'],
            "fUnitID" => $v['store_unit_code'],//常用单位
            "fauxqty" => $v['store_quantity'],
            "fnote" => $v['b_remark'],
            "fAuxPrice" => 0, //含税单价
            "fprc" => 0,//单价
            "famt"=>0,//总价
            "fAuxPlanPrice"=>0,//计划单价
            "fDCStockID" => $warehouseId,//目标仓库
            "fComplexQty" => $v['quantity'].$v['unit']
        ];
        
        if($order_type == 8){
            //调拨，增加来源仓库id 目标仓库id
            $comm_arr['fSCStockID'] = $warehouseId;
            $comm_arr['fDCStockID'] = $v['warehouse_change_id'];
        }    

        //领料退回、直接领料
        if($order_type == 7||$order_type == 11){
            //发料仓库id
            unset($comm_arr['fDCStockID']);
            $comm_arr['fSCStockID'] = $warehouseId;
        }

        //产品入库
        if($order_type == 14&&$procureDetail){
            $comm_arr['fUnitID'] = $v['store_unit_code'];//常用单位
            if($procureDetail['type']==2){
                
                //有调料包,做添加剂包产品入库
                if(isset($procureDetail['tlbag'])&&count($procureDetail['tlbag'])){
                    $comm_arr['fUnitID'] = $procureDetail['tlbag']['FUnitID'];
                    $comm_arr['fQtyMust'] = $procureDetail['tlbag']['FQtyMust'];
                    $comm_arr['fitemId'] = $procureDetail['tlbag']['FItemID'];
                    $comm_arr['fitemNm'] = $procureDetail['tlbag']['FName'];
                    $comm_arr['fqty'] = $procureDetail['tlbag']['FQtyMust'];
                    $comm_arr['fauxqty'] = $procureDetail['tlbag']['FQtyMust'];
                    $comm_arr['fnote'] = '';
                    $comm_arr['fDCStockID'] = 7687;//技术部
                    $comm_arr['fComplexQty'] = $procureDetail['tlbag']['FQtyMust'].$procureDetail['tlbag']['FUnitName'];
                }else{
                    //生产任务单
                    $comm_arr['fSourceTranType'] = 85;//生产任务
                    $comm_arr['fOrderInterID'] = $procureDetail['FInterID'];
                    $comm_arr['fOrderEntryID'] = 0;
                    $comm_arr['fOrderBillNo'] = $procureDetail['warehousing_code'];
                    $comm_arr['fSourceBillNo'] = $procureDetail['warehousing_code'];
                    $comm_arr['fSourceInterId'] = $procureDetail['FInterID'];
                    $comm_arr['fSourceEntryID'] = 0;
                    $comm_arr['fICMOBillNo'] = $procureDetail['warehousing_code'];
                    $comm_arr['fICMOInterID'] = $procureDetail['FInterID'];
                    $comm_arr['fQtyMust'] = $procureDetail['quantity'];//应收数量
                    //$comm_arr['fAuxQtyMust'] = $procureDetail['quantity'];//暂时不传
                }
            }else if($procureDetail['type']==1){
                //mes产品入库
                $comm_arr['fOrderInterID'] = $procureDetail['FInterID'];
                $comm_arr['fOrderEntryID'] = 0;
                $comm_arr['fOrderBillNo'] = $procureDetail['source_code'];
                $comm_arr['fSourceBillNo'] = $procureDetail['source_code'];
                $comm_arr['fSourceTranType'] = 85;//生产任务
                $comm_arr['fSourceInterId'] = $procureDetail['FInterID'];
                $comm_arr['fSourceEntryID'] = 0;
                $comm_arr['fICMOBillNo'] = $procureDetail['source_code'];
                $comm_arr['fICMOInterID'] = $procureDetail['FInterID'];
                $comm_arr['fQtyMust'] = $procureDetail['quantity'];//应收数量
                //$comm_arr['fAuxQtyMust'] = $procureDetail['quantity'];//暂时不传
            }
        }

        //外购入库
        if($order_type == 1 && $procureDetail){
            $comm_arr['fOrderInterID'] = $procureDetail['FInterID'];//采购单表头内码
            $comm_arr['fOrderEntryID'] = $v['row_id'];//$v['auto_id'];
            $comm_arr['fOrderBillNo'] = $procureDetail['warehousing_code'];
            $comm_arr['fSourceBillNo'] = $procureDetail['warehousing_code'];
            $comm_arr['fSourceTranType'] = 71;
            $comm_arr['fSourceInterId'] = $procureDetail['FInterID'];
            $comm_arr['fSourceEntryID'] = $v['row_id'];//$v['auto_id'];
            $comm_arr['fprc'] = $procureDetail['unit_price'];//单价
            $comm_arr['famt'] = round($procureDetail['unit_price']*$v['quantity'],2);//总价
            $comm_arr['fAuxPrice'] = $procureDetail['unit_price'];//含税单价
        }

        //销售出库
        if($order_type == 15 && $procureDetail){  
            $comm_arr['fSourceBillNo'] = $procureDetail['fSourceBillNo'];//发货通知单号
            $comm_arr['fSourceInterId'] = $procureDetail['fsourceinterid'];//发货通知单表头内码
            $comm_arr['fSourceEntryID'] = $procureDetail['fSourceEntryID'];//发货通知单行号
            $comm_arr['fSourceTranType'] = 83;//$procureDetail['crdcode'];//83

            $comm_arr['fOrderInterID'] = $procureDetail['fOrderInterID'];//销售订单内码
            $comm_arr['fOrderBillNo'] = $procureDetail['fOrderBillNo'];//销售订单编码
            $comm_arr['fOrderEntryID'] = $procureDetail['fOrderEntryID'];//销售订单行号
            
            $comm_arr['fUnitID'] = $procureDetail['store_unit_code'];//用发货单的单位
            //$comm_arr['fprc'] = $procureDetail['fAuxPrice'];//单价
            //$comm_arr['famt'] = round($procureDetail['fAuxPrice']*$v['store_quantity'],2);//总价
            //$comm_arr['fAuxPrice'] = $procureDetail['fAuxPrice'];//含税单价
            $comm_arr['fprc'] = 0;
            $comm_arr['famt'] = 0;
            $comm_arr['fAuxPrice'] = 0;
            $comm_arr['FEntrySelfB0180'] = $v['qrNo'];//流水码
        }

        //组件单
        if($order_type == 16){
            $comm_arr['fMtrlType'] = 0;//子件
            if($v['b_remark']=='母件'){
                $comm_arr['fMtrlType'] = 1;//母件
            }
        }

        //$v  如果库区ID=17（原料仓包材区）则回写金蝶数据库转为包材仓（7675）
        //得到转换后的erp仓库id  ,源仓库id
        $erp_warehouse_id_from = Shelves::getErpWarehouseId($v);
        //得到转换后的erp仓库id  ,目标仓库id
        $erp_warehouse_id_to = Shelves::getErpWarehouseId($v,'shelves_change_id');

        if($order_type==8){//调拨
            //原来的仓库是17 就是转原来的仓库id
            if($erp_warehouse_id_from){
                $comm_arr['fSCStockID'] = $erp_warehouse_id_from;
            }
            //调拨，目标库区
            if($erp_warehouse_id_to){
                $comm_arr['fDCStockID'] = $erp_warehouse_id_to;
            }
            
            //都不为false  erp_warehouse_id_to
            if($erp_warehouse_id_to && $erp_warehouse_id_to == $erp_warehouse_id_from){
                return [];
            }
        }else{
            //非调拨，就是目标库区
            if($erp_warehouse_id_from){
                $comm_arr['fDCStockID'] = $erp_warehouse_id_from;
            }

            //领料退回、直接领料
            if($order_type == 7||$order_type == 11){
                //发料仓库id
                if($erp_warehouse_id_from){
                    $comm_arr['fSCStockID'] = $erp_warehouse_id_from;
                }
            }
        }
        ///////
        //金蝶表体
        return $comm_arr;
    }

    /*
     * 回写研究中心生产任务  - 材料出库单  kis
     * 生产任务单，还要做材料出库
     *   */
    public static function kisMaterialOut($u8Head,$v,$back_tlbag = false){
        if(!$u8Head||!$v){
            return ;
        }
        $kis_body = Kisapi::getDataByName('getPPBOM',['fBillNo'=>$v['source_code']],false,false);
        $taskHead = $u8Head;
        $tiaoliaobao_arr = [];
        if($kis_body){
            $comm_arr = [];
            foreach($kis_body as $item){
                $item['FQtyMust'] = $item['FQtyScrap']*$v['quantity'];//上级成品数量*bom单比例，$item['FQtyScrap']
                $item['FAuxQtyMust'] = $item['FQtyScrap']*$v['quantity'];//
                if(stripos($item['FName'],'添加剂')!== false){
                    $tiaoliaobao_arr = $item;//调料包
                }
                
                $comm_arr[] = [
                    "fitemId" => $item['FItemID'],
                    "fitemNm" => $item['FName'],//物料名称
                    "fqty" => $item['FQtyMust'],
                    "fBatchNo" => '',//$item['FBatchNo'],//不需要传批号，得api那边，按先进先出规则扣减库存
                    "fUnitID" => $item['FUnitID'],
                    "fauxqty" => $item['FAuxQtyMust'],
                    "fnote" => '',
                    "fAuxPrice" => 0, //含税单价
                    "fprc" => 0,//单价
                    "famt"=>0,//总价
                    "fAuxPlanPrice"=> $item['FAuxPlanPrice'],//计划单价
                    //"fDCStockID" => $item['FStockID'],//目标仓库
                    "fSCStockID" => $item['FStockID'],//发料仓库
                    "fComplexQty" => $item['FAuxQtyMust'].$item['FUnitName'],
                    "fSourceBillNo" => $item['FSourceBillNo'],
                    "fSourceTranType" => $item['FSourceTranType'],
                    "fSourceInterId" => $item['FSourceInterID'],
                    "fSourceEntryID" => $item['FSourceEntryID'],
                    'fICMOBillNo' => $item['FSourceBillNo'],
                    'fICMOInterID' => $item['FSourceInterID'],
                    'fQtyMust' => $item['FAuxQtyMust']
                ];
            }
            $taskHead['ics24Detail'] = $comm_arr;
            $taskHead['fdept'] = 247;//研发中心
            unset($taskHead['ics02Detail']);//去掉上一个的明细
            //回写数据到金蝶
            $backu8 = config('site.backu8');
            if($backu8){

                //先做添加剂做产品入库处理，仓库入技术部
                if($back_tlbag>0&&$tiaoliaobao_arr){
                    $procureDetail['type'] = 2;
                    $procureDetail['tlbag'] = $tiaoliaobao_arr;
                    $pda = new Pda();
                    $tiaoliaobao_body[] = $pda->erpTableBodyCommon($v,14,$procureDetail);
                    $u8Head['ics02Detail'] = $tiaoliaobao_body;
                    $kis_work_incode = Kisapi::kiscurl('/api/wms/saveStockRm',$u8Head);
                }

                //后材料出库
                $res = Kisapi::kiscurl('/api/wms/saveMaterialOut',$taskHead);
                
                $temporaryModel = new Temporary();
                $temporaryModel->save([
                    'kis_work_outcode' => $res['cCode'],
                    'kis_work_incode' => isset($kis_work_incode['cCode'])?$kis_work_incode['cCode']:''
                ],[
                    'order_code'=>$v['order_code']
                ]);
            }
        }
    }

    public function toAddTemp($sell_order,$main,$v){
        if($sell_order){
                $temporary =   [
                    'auto_id'=>$sell_order['auto_id'],
                    'source_code'=>$main['source_code'],//发货通知单
                    'order_code'=>$main['FBillNo'],
                    'order_date'=>$main['FDate'],
                    'order_list'=>15,
                    'inv_id' => db('inventory')->where('number',$sell_order['inventory_number'])->value('id'),
                    'number'=>$sell_order['inventory_number'],
                    'row_id'=>$sell_order['row_id'],
                    'warehouse_id'=>$main['stock_id'],
                    'shelves_id'=>$v['shelves_id'],
                    'shelves_type'=>2,
                    'quantity'=>$v['fqty'],
                    'store_quantity'=>isset($v['fauxqty'])?$v['fauxqty']:$v['fqty'],
                    'cBatch'=>$v['cBatch'],//批号
                    'status' => 1,
                    'grounding_list'=>1,
                    'createtime'=>date('Y-m-d H:i:s'),
                    'remark' => '',
                    'b_remark' => '',
                    'u8userid' => $main['userid'],//变成wms用户，回写再去取kis用户
                    'u8username' => $main['username'],//变成wms用户，回写再去取kis用户
                    'cDepCode' => isset($main['factory_code'])?$main['factory_code']:'',//kis领料单专用，部门id
                    'cDepName' => isset($main['factory_name'])?$main['factory_name']:'',//kis领料单专用，部门名称
                ];
                db('temporary')->insertGetId($temporary);
        }
    }

    
    public function u8apitest(){
        exit;
        echo 'ok';
        $type = 15;
        $detail_str = '[{"id":16,"FBillNo":"SEOUT240321005","auto_id":"1628794","row_id":1,"local_row_id":0,"inv_number":"4.01.012","inv_name":"橄榄菜(450*24)","inv_specification":"450g*24瓶/箱","inv_attributes":"","inv_unit":"罐","inv_unit_code":"1319","store_unit":"24罐/件","store_unit_code":"1319","fqty":240,"fauxqty":10,"cBatch":"20240314","shelves_id":3,"shelves_type":"undefined","shelves_name":"成品区","b_remark":"","status":1},{"id":17,"FBillNo":"SEOUT240321005","auto_id":"1628795","row_id":2,"local_row_id":1,"inv_number":"4.01.006-1","inv_name":"橄榄菜（180*4*12）彩箱装","inv_specification":"180*4*12瓶/箱","inv_attributes":"","inv_unit":"罐","inv_unit_code":"1337","store_unit":"48罐/件","store_unit_code":"1337","fqty":1440,"fauxqty":30,"cBatch":"20240318","shelves_id":3,"shelves_type":"undefined","shelves_name":"成品区","b_remark":"","status":1},{"id":18,"FBillNo":"SEOUT240321005","auto_id":"1628796","row_id":3,"local_row_id":2,"inv_number":"4.01.046","inv_name":"宜客橄榄菜（450g*2*12）特惠装","inv_specification":"450*2*12罐/件","inv_attributes":"","inv_unit":"罐","inv_unit_code":"1319","store_unit":"24罐/件","store_unit_code":"1319","fqty":936,"fauxqty":39,"cBatch":"20240319","shelves_id":3,"shelves_type":"undefined","shelves_name":"成品区","b_remark":"","status":1},{"id":19,"FBillNo":"SEOUT240321005","auto_id":"1628796","row_id":3,"local_row_id":3,"inv_number":"4.01.046","inv_name":"宜客橄榄菜（450g*2*12）特惠装","inv_specification":"450*2*12罐/件","inv_attributes":"","inv_unit":"罐","inv_unit_code":"1319","store_unit":"24罐/件","store_unit_code":"1319","fqty":24,"fauxqty":1,"cBatch":"20240320","shelves_id":3,"shelves_type":"undefined","shelves_name":"成品区","b_remark":"","status":1}]';
        $detail = json_decode($detail_str,true);
        
        $main['source_code'] = 'WYXOUT033062';
        //20240108针对pda提交上来的销售订单，同物料求和 ，重新整理后，形成新表体
        $sell_temp_arr = [];
        $qrNo_arr = [];
        if($type==15){
            $sell_temp_inv_arr = array_column((array)$detail,'inv_number');//提交上来的物料id数组
            $sell_temp_inv_arr = array_unique($sell_temp_inv_arr);//去掉重复，得到，提交上来的物料编码数组

            //循环旧表体记录，得到上传上来的物料总数（按批号计）
            foreach ($detail as $kk=>$vv){
                if(isset($sell_temp_arr[$vv['inv_number'].'_'.$vv['cBatch']])){
                    $sell_temp_arr[$vv['inv_number'].'_'.$vv['cBatch'].'_'.$vv['shelves_id']] += $vv['fqty'];
                }else{
                    $sell_temp_arr[$vv['inv_number'].'_'.$vv['cBatch'].'_'.$vv['shelves_id']] = $vv['fqty'];
                }

                if(!isset($qrNo_arr[$vv['inv_number'].'_'.$vv['cBatch']])&&$vv['inv_attributes']){
                    $qrNo_arr[$vv['inv_number'].'_'.$vv['cBatch']] = $vv['inv_attributes'];
                }
            }
            //数量，从小-》大，排列，方便下面扣减
            asort($sell_temp_arr);
            //dump($sell_temp_arr);
            //得到所有提交上来的发货通知单明细
            $sell_order_arr = collection(MaterialListView::where([
                'material_code' => $main['source_code'],
                'inventory_number' => ['IN',$sell_temp_inv_arr],
                'status' => 1
            ])
            ->field('auto_id,row_id,inventory_number,no_quantity,fCoefficient')
            ->select())
            ->toArray();

            dump($sell_temp_arr);
            
            $deal_data = [];//新的表体明细，拆分好的
            if($sell_temp_arr&&$sell_order_arr){
                foreach($sell_temp_arr as $sk=>&$total_fqty){
                    $sk_arr = explode('_',$sk);//编码_批号_库区
                    foreach($sell_order_arr as &$sell_order){
                        if($sell_order['no_quantity']>0){
                            if($sell_order['inventory_number'] == $sk_arr[0]){
                                //同个物料,插入临时表
                                $thisqty = $sell_order['no_quantity'];
                                $total_fqty -= $sell_order['no_quantity'];
                                
                                if($total_fqty<0){
                                    $thisqty = $sell_order['no_quantity']+$total_fqty;
                                    $total_fqty = 0;
                                    $sell_order['no_quantity'] -= $thisqty;
                                }else{
                                    $sell_order['no_quantity'] = 0;
                                }
                                
                                
                                if($thisqty){
                                    //本次操作数量大于0的，加入临时数组
                                    $deal_data[] = [
                                        'auto_id' => $sell_order['auto_id'],
                                        'row_id' => $sell_order['row_id'],
                                        'cBatch'=>$sk_arr[1],
                                        'shelves_id' => $sk_arr[2],
                                        'fqty' => $thisqty,
                                        'fauxqty' => $thisqty/$sell_order['fCoefficient'],
                                        'inv_number' =>$sell_order['inventory_number'],
                                        'qrNo' => isset($qrNo_arr[$sk_arr[0].'_'.$sk_arr[1]])?$qrNo_arr[$sk_arr[0].'_'.$sk_arr[1]]:''
                                    ];
                                }
                            }
                        }
                    }
                    if($total_fqty<=0){
                        continue;
                    }
                }
                
            }
            //按行号排序
            array_multisort(array_column($deal_data, 'row_id'),SORT_ASC,$deal_data);
            //重新赋值表体
            $detail = $deal_data;
        }
    }
}